package com.zerui.manager.mq;

import com.alibaba.fastjson2.JSON;
import com.zerui.manager.access.auth.task.domain.AuthTaskDetail;
import com.zerui.manager.access.auth.task.gateway.AuthTaskGateway;
import com.zerui.manager.common.mq.consumer.DeviceIotEventMessage;
import com.zerui.manager.common.mq.consumer.DeviceIotEventRecord;
import com.zerui.manager.devciecurfewtimelog.DeviceCurfewtimeLog;
import com.zerui.manager.devciecurfewtimelog.gateway.DeviceCurfewtimeLogGateWay;
import com.zerui.manager.device.Device;
import com.zerui.manager.device.gatewayimpl.DeviceGateWayImpl;
import com.zerui.manager.web.enums.DeviceAccessStatusEnum;
import com.zerui.manager.web.enums.SuccessAndFailureEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Author lvfengjun
 * @create_time 2023-10-23 17:10
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.consumer.group}-deviceCurfew", topic = "iot-event")
public class DeviceCurfewTimeRocketMqConsumer implements RocketMQListener<DeviceIotEventMessage> {

	@Resource
	private DeviceCurfewtimeLogGateWay deviceCurfewtimeLogGateWay;

	@Resource
	private DeviceGateWayImpl deviceGateWay;

	@Resource
	private AuthTaskGateway authTaskGateway;

	@Override
	public void onMessage(DeviceIotEventMessage deviceIotEventMessage) {
		log.info("deviceIotEventMessage 处理物联网关获取实时状态 报文 msg {}", deviceIotEventMessage);
		// 处理门禁开关状态落库
		Long deviceId = deviceIotEventMessage.getDeviceId();
		if (ObjectUtils.isNotEmpty(deviceId)) {
			//只处理对应的行为事件返回数据
			DeviceIotEventRecord data = deviceIotEventMessage.getData();
			String action = data.getAction();
			log.info("设备id -> {} 报文内容 -> data {} ", deviceId, data);
			if (StringUtils.isEmpty(action)) {
				return;
			}
			if (StringUtils.equals(DeviceAccessStatusEnum.INSERT_PERSON.getAction(), action)) {
				// 添加人员返回
				insertPersonResult(deviceIotEventMessage);
			} else if (StringUtils.equals(DeviceAccessStatusEnum.REMOVE_PERSON.getAction(), action)) {
				// 删除人员返回
				removePersonResult(deviceIotEventMessage);
			} else if (StringUtils.equals(DeviceAccessStatusEnum.OPEN.getAction(), action)
					|| StringUtils.equals(DeviceAccessStatusEnum.CLOSE.getAction(), action)) {
				/**
				 * 判断行为是否为开关门禁 指令
				 * 如果是开关门禁人脸识别指令 记录到日志表中 并改变device 主表中门禁数据状态
				 */
				DeviceCurfewtimeLog deviceCurfewtimeLog = new DeviceCurfewtimeLog();
				deviceCurfewtimeLog.setDeviceId(deviceId);
				deviceCurfewtimeLog.setDeviceName(deviceIotEventMessage.getDeviceName());
				deviceCurfewtimeLog.setAction(DeviceAccessStatusEnum.getNameByAction(action));
				deviceCurfewtimeLog.setResult(data.getResult() ?
						SuccessAndFailureEnum.SUCCESS.getName()
						: SuccessAndFailureEnum.FAILURE.getName());
				deviceCurfewtimeLog.setErrMessage(data.getErrMessage());
				deviceCurfewtimeLog.setMsgTime(deviceIotEventMessage.getTime());
				deviceCurfewtimeLog.setCreateTime(LocalDateTime.now());
				//原始报文要加到 日志表中
				deviceCurfewtimeLog.setMsg(data.toString());

				deviceCurfewtimeLogGateWay.add(deviceCurfewtimeLog);
				//判断是否成功 改变数据库中 对应的人脸识别状态
				if (data.getResult()) {
					Device device = new Device();
					device.setDeviceId(deviceId);
					//开还是关
					device.setCurfewStatus(DeviceAccessStatusEnum.getNameByAction(action));
					deviceGateWay.updateByDeviceId(device);
				}
			}
		}
		log.info("物联网关报文处理结束 设备id {}", deviceId);
	}

	private void removePersonResult(DeviceIotEventMessage deviceIotEventMessage) {
		syncResult(deviceIotEventMessage);
	}

	private void syncResult(DeviceIotEventMessage deviceIotEventMessage) {
		DeviceIotEventRecord data = deviceIotEventMessage.getData();
		String requestId = data.getRequestId();
		AuthTaskDetail detail = authTaskGateway.getDetailByRequestId(requestId);
		if (detail != null) {
			if (data.getResult()) {
				this.authTaskGateway.syncSuccess(detail.success());
			} else {
				String errMsg;
				if (StringUtils.isEmpty(data.getErrMessage())) {
					String output = JSON.toJSONString(data.getOutput());
					if (output.length() > 200) {
						errMsg = output.substring(0, 200);
					} else {
						errMsg = output;
					}
				} else {
					errMsg = data.getErrMessage();
				}
				this.authTaskGateway.syncFailure(detail.failure(errMsg));
			}
		}
	}

	private void insertPersonResult(DeviceIotEventMessage deviceIotEventMessage) {
		syncResult(deviceIotEventMessage);
	}
}
